package cn.wen.base.adapter.viewpager;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * ViewPager的一个通用Adapter
 */

public class QuickPagerAdapter<T> extends PagerAdapter {
    private List<T> mData;// 数据
    private PagerHolderCreator mCreator;// 创建View的构建器
    private List<View> mConvertViews;// 复用View的集合
    private boolean mIsLopper;

    public QuickPagerAdapter(List<T> data, PagerHolderCreator creator, boolean isLopper) {
        this.mData = data == null ? new ArrayList<T>() : new ArrayList<T>(data);
        this.mCreator = creator;
        mConvertViews = new ArrayList<>();
        this.mIsLopper = isLopper;
    }

    public QuickPagerAdapter(List<T> data, PagerHolderCreator creator) {
        this(data, creator, true);
    }

    @Override
    public int getCount() {
        if (!mIsLopper) {
            return mData.size();
        }
        return mData.size() > 1 ? Integer.MAX_VALUE : mData.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // 处理一下Position

        position = position % mData.size();


        PagerHolder holder = null;
        // 3. 复用
        View view = getConvertView();
        if (view == null) {
            holder = mCreator.createViewPagerHolder();
            view = holder.onCreateView(container.getContext());
            if (view != null) {
                // 缓存View
                view.setTag(holder);
            }
        } else {
            holder = (PagerHolder) view.getTag();
            //Log.e("TAGS", "利用了........" + view);
        }
        container.addView(view);
        if (holder != null && view != null) {
            holder.onBind(container.getContext(), position, mData.get(position));
        }
        return view;
    }

    /**
     * 获取缓存View来复用
     */
    private View getConvertView() {
        for (View convertView : mConvertViews) {
            if (convertView.getParent() == null) {
                // 说明View被移除了--》可以复用
                return convertView;
            }
        }
        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // 1.移除View
        container.removeView((View) object);
        // 2.添加到复用的View里面去
        mConvertViews.add((View) object);
    }


    public int getDataSize() {
        return mData.size();
    }

    /**
     * 轮播图专用
     */
    public String getBannerDesc(int position) {
        return null;
    }

    public T getData(int position) {
        return mData.get(position);
    }


    public void setLoop(boolean isLoop) {
        this.mIsLopper = isLoop;
    }
}
